/* =================================================
 * Package:			dk.iha.toksEditor
 * File:			UnfinishedPatientActivity.java
 * Description:		This is the activity for which
 * 					is responsible for showing which
 * 					patients TOKS is not finished.
 * 
 * Responsible
 * =================================================
 * Name:			Vinnie Juul
 * Study number:	09767
 */

package dk.iha.toksEditor;

import java.util.ArrayList;
import java.util.Date;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class UnfinishedPatientActivity extends ListActivity {
	/**
	 * Attributes use in class
	 */
	private ListView mPatientListView;
	private ArrayList<Patient> patientList;
	private UnfinishedPatientAdapter upAdapter;
	private Boolean showCheckBox;
	private Button canceled;
    private Button remove;
	
	/**
	 * Attributes use to DBAdapber
	 */
	private DBAdapter database;
	private final String PATIENT_NAME = "patientName";
	private final String PATIENT_CPR = "patientCPR";
	private final String PATIENT_UPDATE_DATE = "patientUpdatedDate";
	
	/**
	 * Attributes use to AsyncTask
	 */
	public final String LOAD_PATIENTS = "loadPatients";
	public final String REMOVE_PATIENS = "1";
	public String asyncCaller;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		patientList = new ArrayList<Patient>();
		showCheckBox = false;
		setContentView(R.layout.favorite_patients_view);
		mPatientListView = getListView();
		upAdapter = new UnfinishedPatientAdapter(getApplicationContext(), R.layout.favorite_patients_row, patientList);
		mPatientListView.setAdapter(upAdapter);
		database = new DBAdapter(this);
		
		canceled = (Button)findViewById(R.id.canceledButton);
        remove = (Button)findViewById(R.id.removeButton);
        
		TextView headline = (TextView)findViewById(R.id.FavoritePatientList);
		headline.setText(getText(R.string.UnfinishedPatientHeadline));
		
        getUnfinishedPatients();
	}
	
	@Override
	public void onBackPressed() {
	    if(showCheckBox){
	        showCheckBox = false;
	        upAdapter.notifyDataSetChanged();
	    }else{
	        super.onBackPressed();
	    }
	}
	
	@Override
	protected void onResume() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		if(prefs.getBoolean("checkboxPref", false))
		{
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		}
		
		else
		{
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		}
		super.onResume();
	}
	
	@Override
	protected void onRestoreInstanceState(Bundle state) {
		super.onRestoreInstanceState(state);
		showCheckBox = state.getBoolean("ShowCheckBox", false);
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putBoolean("ShowCheckBox", showCheckBox);
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) 
	{		
		super.onListItemClick(l, v, position, id);
		Intent intent = new Intent();
		intent.putExtra("patient",patientList.get(position));
		setResult(RESULT_OK, intent);
		finish();
	}
	

	@Override
	public boolean onPrepareOptionsMenu (Menu menu) {
	    if (showCheckBox){
	        menu.getItem(0).setEnabled(false);
	    }else{
	    	menu.getItem(0).setEnabled(true);
	    }
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.remove:
	        	showCheckBox = true;
        		showRemoveButtons();
        		upAdapter.notifyDataSetChanged();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	/**
	 * Create the menu and show it
	 * @param Menu
	 */
	public boolean onCreateOptionsMenu(Menu menu) 
	{
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.unfinished_patients_menu, menu);
	    return true;
	}
	
	/**
	 * Remove the selected patient form list
	 * @param view - the button view
	 */
	public void removeSelected(View view){
		asyncCaller = REMOVE_PATIENS;
		AsyncDBConnection asyncDBC = new AsyncDBConnection();
		asyncDBC.execute(REMOVE_PATIENS);
	}
	
	/**
	 * Cancel removing any patient from list
	 * @param View - the button view
	 */
	public void canceled(View View)
	{
		showCheckBox = false;
		showRemoveButtons();
		upAdapter.notifyDataSetChanged();
	}
	
	/**
	 * Show the button used when selecting patients to be removed
	 * from list.
	 * The button is only visible if showCheckBox is true
	 */
	public void showRemoveButtons(){
		if(canceled != null && remove != null){
			if(showCheckBox){
	        	canceled.setVisibility(View.VISIBLE);
				remove.setVisibility(View.VISIBLE);
	        }
		}
	}

	/**
	 * Collecting unfinished patient form database
	 */
	private void getUnfinishedPatients() {		
		asyncCaller = LOAD_PATIENTS;
		AsyncDBConnection asyncDBC = new AsyncDBConnection();
		asyncDBC.execute(LOAD_PATIENTS); 
		
	}
	
	/**
	 * Class use to make Custom listview
	 * @author Vinnie Juul
	 *
	 */
	private class UnfinishedPatientAdapter extends ArrayAdapter<Patient> {

		private ArrayList<Patient> mItems;
		public UnfinishedPatientAdapter(Context context, int textViewResourceId,
				ArrayList<Patient> items) {
			super(context, textViewResourceId, items);
			mItems = items;
		}
		
		 @Override
	     public View getView(final int position, View convertView, ViewGroup parent) {
	        View v = convertView;
	        if (v == null) {
	        	LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	        	v = vi.inflate(R.layout.favorite_patients_row, null);
	        }
	        Patient FP = mItems.get(position);
	        if(FP != null){
	          	TextView name = (TextView)v.findViewById(R.id.NameTextView);
	           	TextView cpr = (TextView)v.findViewById(R.id.CprTextView);
	            TextView date = (TextView)v.findViewById(R.id.DateTextView);
	            if(name != null){
	            	name.setText(FP.getName());
	            }
	            if(cpr != null){
	            	cpr.setText(FP.getEasyCPR());
	            }
	            if(date != null){
	            	date.setText(getDateAsString(FP.getLastUpdated()));
	                date.setVisibility(View.VISIBLE);
	            }
	        }      
	                
	        final CheckBox box = (CheckBox)v.findViewById(R.id.RemoveCheckBox);
	               
			if(showCheckBox == true){
				box.setVisibility(View.VISIBLE);
				box.setChecked(FP.getIsChecked());
			}else{
				box.setVisibility(View.INVISIBLE);
				canceled.setVisibility(View.GONE);
				remove.setVisibility(View.GONE);
			}
	               
	        box.setOnClickListener(new OnClickListener() {
	        	@Override
				public void onClick(View v) {
	        		if(box.isChecked()){
						patientList.get(position).setIsChecked(true);
					}else{
						patientList.get(position).setIsChecked(false);
					}	
				}
			});
							
	       	return v;
		 }
		 
		 /**
		  * Find the weekday for the date
		  * @param d - the last updated date
		  * @return the weekday for the date
		  */
		 private String getDateAsString(Date d){
			 String day;
			 
			 switch(d.getDay()){
			 case 1: day = getString(R.string.TimeDayMonday); break;
			 case 2: day = getString(R.string.TimeDayTuesday); break;
			 case 3: day = getString(R.string.TimeDayWednesday); break;
			 case 4: day = getString(R.string.TimeDayThursday); break;
			 case 5: day = getString(R.string.TimeDayFriday); break;
			 case 6: day = getString(R.string.TimeDaySaturday); break;
			 case 7: day = getString(R.string.TimeDateSunday); break;
			 default: day = "ERROR";
			 }

			 String date = day + " " + d.getDate() + "/" + (d.getMonth()-1) + "-" + (d.getYear() + 1900);
			 
			 return date;
		 }
	}
	
	/**
	 * Use to run function calls asynchronous
	 * @author Vinnie Juul
	 *
	 */
	private class AsyncDBConnection extends AsyncTask<String, Integer, Boolean>
	{
		private boolean succeded = false;
		private boolean emptyList = false;
		private ProgressDialog mpd;

		@Override
		protected void onPreExecute() {
			if(asyncCaller.equals(LOAD_PATIENTS)){
				mpd = ProgressDialog.show(UnfinishedPatientActivity.this, getString(R.string.FavoritePatientProgressDialogTitle), getString(R.string.FavoritePatientProgressDialogTextLoad), true, true);	
				
			}else if(asyncCaller.equals(REMOVE_PATIENS)){
				mpd = ProgressDialog.show(UnfinishedPatientActivity.this, getString(R.string.FavoritePatientProgressDialogTitle), getString(R.string.FavoritePatientProgressDialogTextRemove), true, true);	
			}
			
			mpd.setOnCancelListener(new OnCancelListener() {
				
				@Override
				public void onCancel(DialogInterface dialog) {
					Intent intent = new Intent();
					setResult(RESULT_CANCELED, intent);
					finish();
				}
			});
			super.onPreExecute();
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			succeded = true;
			emptyList = false;
			if(params[0].equals(LOAD_PATIENTS)){
				database.openReadOnly();
				Cursor c = database.getAllItemsCursor();
				c.moveToFirst();
				do{
					Patient p = new Patient(c.getString(c.getColumnIndex(PATIENT_CPR)), c.getString(c.getColumnIndex(PATIENT_NAME)));
					p.setLastUpdated(new Date(c.getLong(c.getColumnIndex(PATIENT_UPDATE_DATE))));
					patientList.add(p);
				}while(c.moveToNext());
				database.close();
				if(patientList.size() == 0){
					succeded = false;
				}
			}else if(params[0].equals(REMOVE_PATIENS)){
				database.open();
				for(int i = 0; i < patientList.size(); i++){
					if(patientList.get(i).getIsChecked() == true){
						if(database.removePatient(patientList.get(i))){
							patientList.remove(i);
							i--;
						}
						else{
							succeded = false;
						}
					}
				}
				database.close();
				showCheckBox = false;
			}
			if(patientList.size() == 0){
				emptyList = true;
			}
			return succeded;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			mpd.dismiss();
			upAdapter.notifyDataSetChanged();
			if(asyncCaller.equals(LOAD_PATIENTS) && succeded == false)
			{
				setResult(RESULT_CANCELED, new Intent());
				finish();
				Toast.makeText(getApplicationContext(), getString(R.string.PatientListNoPatientOrConnection), Toast.LENGTH_SHORT).show();
			}else if(asyncCaller.equals(REMOVE_PATIENS) && emptyList == true)
			{
				setResult(RESULT_CANCELED, new Intent());
				finish();
				Toast.makeText(getApplicationContext(), getString(R.string.PatientListNoPatientLeft), Toast.LENGTH_SHORT).show();
			}
			
			super.onPostExecute(result);
		}
	}
}
